package cn.ac.jaas.ljx.mybatis;

import java.io.InputStream;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class MySqlSessionFactory {

    private static SqlSessionFactory sqlSessionFactory;
    
    
    public static SqlSessionFactory getSqlSessionFactoryByXml() {
        if(sqlSessionFactory == null) {
            try {
                InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }
    
    
    public static SqlSessionFactory getSqlSessionFactoryByJava() {
        if(sqlSessionFactory == null) {
            DataSource dataSource = MySqlSessionFactory.DataSourceFactpry.getPooledDataSource();
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("dev", transactionFactory, dataSource);
            Configuration configuration = new Configuration(environment);
            configuration.getTypeAliasRegistry().registerAliases("cn.ac.jaas.ljx.mybatis.model");
            configuration.getTypeHandlerRegistry().register("cn.ac.jaas.ljx.mybatis.model.typeHandler");
            configuration.addMappers("cn.ac.jaas.ljx.mybatis.dao");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        }
        return sqlSessionFactory;
    }
    
    public static SqlSession openSession() {
        return getSqlSessionFactoryByXml().openSession();
    }
    
    static class DataSourceFactpry {
        public static DataSource getPooledDataSource() {
            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/test";
            String username = "root";
            String password = "123456";
            PooledDataSource dataSource = new PooledDataSource(driver, url, username, password);
            return dataSource;
        }
    }
}
